/**
 * 定义全局变量
 * @param userName 用户名称
 * @param status 用户状态
 * @param roleId 角色id
 * @param  firstdate 开始时间
 * @param  enddate 结束时间
 * @param  deptId 部门id
 */
var userName = "",
    status = "",
    roleId = "",
    befdate = "",
    enddate = "",
    deptId = "";
/**
 * 初始化
 */
$(function () {
    // 滚动条高度
    setiWheelStepH();
    searchInit();
    init();
    tableInit();
});

/**
 * 加载搜索功能初始化
 */
function searchInit() {
    $.ajax({
        url: prefixRole + "/findAll",
        type: "get",
        async: false,
        success: function (data) {
            var errcode = data.errcode;
            var errmsg = data.errmsg;
            if (errcode == "0") {
                var data = data.data.roles;
                for (var i = 0; i < data.length; i++) {
                    var option = "<option value=\"" + data[i].roleId + "\">" + data[i].roleName + "</option>";
                    $("#roles").append(option);
                }
            } else {
                AjaxException(errmsg);
            }
        },
        error: function () {
            AjaxErro();
        }
    })
}

/**
 * 加载layui样式
 */
function init() {
    layui.use(['form', 'laydate', 'dtree'], function () {

        var form = layui.form
            , laydate = layui.laydate
            , dtree = layui.dtree
            , nowdate = getNowFormatDate();

        //年月日范围选择选择器
        laydate.render({
            elem: '#month'
            , max: 'nowdate'
            , range: '至'
            , done: function (value) {
                if (value != null && (value.indexOf("至") != -1)) {
                    var date = value.split("至");
                    //  开始日期
                    befdate = date[0].trim();
                    //   结束日期
                    enddate = date[1].trim();
                } else {
                    befdate = "";
                    enddate = "";
                }
            }
        });

        //账号状态选择
        form.on('select(status)', function (data) {
            //  状态值
            if (data.value != null) {
                status = data.value;
            }
        });

        //角色选择
        form.on('select(roles)', function (data) {
            //  角色值
            if (data.value != null) {
                roleId = data.value;
            }
        });

        //  部门树
        var d = dtree.render({
            elem: "#deptTree",
            spread: true,
            //initLevel: 1,
            url: prefixDept + "/userdtreedate",
            type: "all",
            async: false  // 只需将该参数设置为false，即可同步加载
        });

        // 点击节点名称获取选中节点值
        dtree.on("node('deptTree')", function (param) {
            deptId = param.nodeId;
            tableInit();
        });


    });
}

// 数据展示
function tableInit() {
    layui.use(['form', 'table'], function () {
        var loading = window.top.layer.load(0, {shade: false});

        var form = layui.form
            , table = layui.table;

        //展示已知数据
        table.render({
            elem: '#tb'
            , url: prefixUser + "/list"
            , toolbar: '#toolbar'
            , where: {
                //  设置参数
                "params": JSON.stringify({
                    "userName": userName,
                    "status": status,
                    "roleId": roleId,
                    "befdate": befdate,
                    "enddate": enddate,
                    "deptId": deptId,
                })
            }
            , cellMinWidth: 200
            , cols:
                [[
                    {checkbox: true, fixed: 'true'}
                    , {type: 'numbers', title: '序号', fixed: 'true'}
                    , {field: 'loginName', title: '登录名称', fixed: 'true'}
                    , {field: 'userName', title: '用户名称', fixed: 'true'}
                    , {
                        field: 'sex', title: '性别',
                        templet: function (d) {
                            switch (d.sex) {
                                case "0" :
                                    return "<span>男</span>";
                                case "1" :
                                    return "<span style=\"color: #F581B1;\">女</span>"
                                default:
                                    return "<span style=\"color: #f51900;\">未知</span>";
                            }
                        }
                    }
                    , {field: 'deptName', title: '部门'}
                    , {field: 'phonenumber', title: '手机号码'}
                    , {field: 'email', title: '邮箱'}
                    , {
                        field: 'status', title: '帐号状态',
                        templet: function (d) {
                            switch (d.status) {
                                case "0" :
                                    return "<button class=\"layui-btn layui-btn-sm\">正常</button>";
                                case "1" :
                                    return "<button class=\"layui-btn layui-btn-sm layui-btn-warm\">停用</button>";
                                default:
                                    return "<button class=\"layui-btn layui-btn-sm layui-btn-danger\">异常</button>";
                            }

                        }
                    }
                    , {field: 'createTime', title: '创建时间'}
                    , {fixed: 'right', align: 'center', toolbar: '#tool'}
                ]]
            , page:
                true //是否显示分页
            , limits:
                [10, 20, 30]
            , limit:
                10 //每页默认显示的数量
            , done:
                function () {
                    layTool.toplayer.close(loading);
                }
        });

        //头工具栏事件
        table.on('toolbar(tb)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'insert':
                    insert();
                    break;

                case 'remove':
                    var data = checkStatus.data;
                    remove(data);
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(tb)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            switch (obj.event) {
                case 'update':
                    update(data);
                    break;
                case 'operate':
                    //重置密码
                    operate(data);
                    break;
            }
        });

    })
}


/**
 * @Description:    查询事件
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/7
 */

function serach() {
    //  用户名称
    userName = $("#userName").val();
    tableInit();
}

/**
 * @Description:    添加操作
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/7
 */

function insert() {
    var title = "新增用户信息",
        url = prefixOpen + "/web!system!user!user_insert",
        width = "30%",
        height = "70%";
    //  打开新窗口
    layTool.openDialog(title, url, width, height, insertOk);
}

/**
 *  保存用户点击事件save
 */
function insertOk(index, layero) {
    // 获取子类窗口的form 表单
    var body = layTool.getChildFrame("body", index);
    var form = $(body[0]).find('#form');
    if (validate_form(form[0])) {
        var formObj = form.serializeArray();
        // 发送保存地址
        $.ajax({
            url: prefixUser + "/insert",
            data: formObj,
            type: "POST",
            beforeSend: function () {
                loading = layTool.toplayer.load(0, {shade: false});
            },
            success: function (data) {
                layTool.toplayer.close(loading);
                var errcode = data.errcode;
                var errmsg = data.errmsg;
                if (errcode == "0") {
                    tableInit();
                    layTool.closeLayer(index);
                    layTool.showSucAlert(errmsg);
                } else {
                    layTool.showAlert(errmsg);
                }

            },
            error: function (e) {
                layTool.toplayer.close(loading);
                AjaxErro();
            }
        })
    }
}

/**
 * @Description:    更新操作
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/7
 */

function update(data) {
    var userId = data.userId;
    var title = "修改用户信息",
        url = prefixUser + "/openUserUpdate?userId=" + userId,
        width = "30%",
        height = "65%";
    //  打开新窗口
    layTool.openDialog(title, url, width, height, updateOk);
}

/**
 * @Description: 确定更新事件回调
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/7
 */
function updateOk(index, layero) {
    // 获取子类窗口的form 表单
    var body = layTool.getChildFrame("body", index);
    var form = $(body[0]).find('#form');
    if (validate_form(form[0])) {
        var formObj = form.serializeArray();
        // 发送保存地址
        $.ajax({
            url: prefixUser + "/update",
            data: formObj,
            type: "POST",
            beforeSend: function () {
                loading = layTool.toplayer.load(0, {shade: false});
            },
            success: function (data) {
                layTool.toplayer.close(loading);
                var errcode = data.errcode;
                var errmsg = data.errmsg;
                if (errcode == "0") {
                    tableInit();
                    layTool.closeLayer(index);
                    layTool.showSucAlert(errmsg);
                } else {
                    layTool.showAlert(errmsg);
                }

            },
            error: function (e) {
                layTool.toplayer.close(loading);
                AjaxErro();
            }
        })
    }
}

/**
 * @Description:   删除操作
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/8
 */

function remove(data) {
    if (!isEmpty(data)) {
        var dataLength = data.length;

        if (dataLength > 0) {
            layTool.showConfirm("确定要删除您选择的" + dataLength + "个用户吗？", function () {
                var loading = "";
                var userIds = "";
                for (var i = 0; i < dataLength; i++) {
                    userIds += data[i].userId + ",";
                }
                $.ajax({
                    url: prefixUser + "/deleteUser",
                    data: {
                        userIds: userIds.substring(0, userIds.length - 1)
                    },
                    beforeSend: function () {
                        loading = layTool.toplayer.load(0, {shade: false});
                    },
                    success: function (data) {
                        layTool.toplayer.close(loading);
                        if (!isEmpty(data)) {
                            var errcode = data.errcode;
                            var errmsg = data.errmsg;
                            if (errcode == "0") {
                                tableInit();
                                layTool.showSucAlert(errmsg);
                            } else {
                                layTool.showAlert(errmsg);
                            }
                        }
                    },
                    error: function () {
                        layTool.toplayer.close(loading);
                        AjaxErro();
                    }
                })

            });
        } else {
            layTool.showMsg("只能同时选择1个或多个用户，您选择了" + dataLength + "个");
        }
    } else {
        layTool.showMsg("请选择要删除的用户信息");
    }

}

/**
 * @Description: 重置密码
 * @Param:
 * @return:
 * @Author: Mr.Yan
 * @Date: 2018/12/10
 */

function operate(data) {
    var userId = data.userId;
    var userName = data.userName;
    layTool.showConfirm("确定要重置您选择的'" + userName + "'用户的密码吗？", function () {
        $.ajax({
            url: prefixUser + "/operatePass",
            data: {
                userId: userId
            },
            beforeSend: function () {
                loading = layTool.toplayer.load(0, {shade: false});
            },
            success: function (data) {
                layTool.toplayer.close(loading);
                if (!isEmpty(data)) {
                    var errcode = data.errcode;
                    var errmsg = data.errmsg;
                    if (errcode == "0") {
                        layTool.showSucAlert(errmsg);
                    } else {
                        layTool.showAlert(errmsg);
                    }
                }
            },
            error: function () {
                layTool.toplayer.close(loading);
                AjaxErro();
            }
        })
    });
}
